package com.chongqing.shiro.web.controller;


import com.chongqing.shiro.model.entity.Permission;
import com.chongqing.shiro.model.vo.ResponseVo;
import com.chongqing.shiro.model.vo.ResultUtil;
import com.chongqing.shiro.service.PermissionService;
import com.chongqing.shiro.service.filter.FilterChainDefinitions;
import com.chongqing.shiro.util.CoreConst;
import com.chongqing.shiro.util.VerificationUtil;
import org.apache.tomcat.util.bcel.Const;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 权限控制器
 * -------------------
 * @Author: YangXingfu
 * @Date: 2019/02/11 16:18
 */

@Controller
@RequestMapping("/permission")
public class PermissionController {


    private static final Logger log = LoggerFactory.getLogger(PermissionController.class);

    /**
     * 1:全部资源， 2：菜单资源
     */
    private static final String[] MENU_FLAG = {"1", "2"};

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private FilterChainDefinitions filterChainDefinitions;

    /**
     * 权限列表数据
     */
    @PostMapping("/list")
    @ResponseBody
    public List<Permission> loadPermissions(String flag) {
        List<Permission> permissionList = new ArrayList<>();
        if (VerificationUtil.isEmpty(flag) || MENU_FLAG[0].equals(flag)) {
            permissionList = permissionService.selectAll(CoreConst.STATUS_VALID);
        } else {
            permissionList = permissionService.selectAllMenuName(CoreConst.STATUS_VALID);
        }
        return permissionList;
    }


    /**
     * 添加权限
     */
    @ResponseBody
    @PostMapping("/add")
    public ResponseVo addPermission(Permission permission) {
        try {
            int a = permissionService.insert(permission);
            if (a > 0) {
                filterChainDefinitions.updatePermissions();
                ;
                return ResultUtil.success("添加权限成功");
            } else {
                return ResultUtil.error("添加权限失败");
            }
        } catch (Exception e) {
            log.error(String.format("PermissionController.addPermission%s", e));
            throw e;
        }
    }

    /**
     * 编辑权限详情
     */
    @GetMapping("/edit")
    public String detail(Model model, String permissionId) {
        Permission permission = permissionService.findByPermissionId(permissionId);
        if (permission != null) {
            if (permission.getParentId().equals(CoreConst.TOP_MENU_ID)) {
                model.addAttribute("parentName", CoreConst.TOP_MENU_NAME);
            } else {
                Permission parent = permissionService.findById(permission.getParentId());
                model.addAttribute("parentName", parent.getParentId());
            }

        }
        model.addAttribute("permission", permission);
        return "permission/detail";
    }

    /**
     * 编辑权限
     */
    @ResponseBody
    @PostMapping("/edit")
    public ResponseVo editPermission(@ModelAttribute("permission") Permission permission) {
        int a = permissionService.updateByPermissionId(permission);
        if (a > 0) {
            filterChainDefinitions.updatePermissions();
            return ResultUtil.success("编辑权限成功");
        } else {
            return ResultUtil.error("编辑权限失败");
        }
    }

    /**
     * 删除权限
     */
    @ResponseBody
    @PostMapping("/delete")
    public ResponseVo deletePermission(String permissionId) {
        try {
            int subPermByPermissionIdCont = permissionService.selectSubPermsByPermissionId(permissionId);
            if (subPermByPermissionIdCont > 0) {
                return ResultUtil.error("该资源存在下级资源，无法删除！");
            }
            int a = permissionService.updateStatus(permissionId, CoreConst.STATUS_INVALID);
            if (a > 0) {
                filterChainDefinitions.updatePermissions();
                return ResultUtil.success("删除权限成功");
            } else {
                return ResultUtil.error("删除权限失败");
            }
        } catch (Exception e) {
            log.error(String.format("PermissionController.deletePermission%s", e));
            throw e;
        }
    }

}